//
//  PlayVideoViewController.m
//  VideoRecord
//
//  Created by guimingsu on 15/4/27.
//  Copyright (c) 2015年 guimingsu. All rights reserved.
//

#import "PlayVideoViewController.h"
#import <AVFoundation/AVFoundation.h>
#import "MBProgressHUD.h"
#import "NetManager.h"
#import "Tools.h"
#import "ConfigData.h"
#import "ASIFormDataRequest.h"
#import "Thud.h"

@interface PlayVideoViewController ()<UITextFieldDelegate>{
    UITextField *tf;
}

@property (strong , nonatomic) MBProgressHUD * hud;
@property (strong , nonatomic) NSString * video_path;
@property (strong , nonatomic) UIImage *saveImage;
@property (strong , nonatomic) NSString *img_path;

@end

@implementation PlayVideoViewController
{

    AVPlayer *player;
    AVPlayerLayer *playerLayer;
    AVPlayerItem *playerItem;
    
    UIImageView* playImg;
    
}

@synthesize videoURL;


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"发布视频";
    
    float videoWidth = 80;

    
    AVAsset *movieAsset = [AVURLAsset URLAssetWithURL:videoURL options:nil];
    playerItem = [AVPlayerItem playerItemWithAsset:movieAsset];
    player = [AVPlayer playerWithPlayerItem:playerItem];
    
    playerLayer = [AVPlayerLayer playerLayerWithPlayer:player];
    playerLayer.frame = CGRectMake(10, 10, videoWidth, videoWidth);
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
    playerLayer.backgroundColor = [UIColor lightGrayColor].CGColor;
    [self.view.layer addSublayer:playerLayer];
    
    UITapGestureRecognizer *playTap=[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(playOrPause)];
    [self.view addGestureRecognizer:playTap];
    
    [self pressPlayButton];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playingEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:nil];
    
    CGRect frame_img= CGRectMake(0,(44-19)/2,19,19);
    UIImageView* backView=[[UIImageView alloc] initWithFrame:frame_img];
    backView.image=[UIImage imageNamed:@"back2016"];
    CGRect frameBtn= CGRectMake(0, 0,50, 44);
    UIButton* homeBtn= [[UIButton alloc] initWithFrame:frameBtn];
    [homeBtn addTarget:self action:@selector(backFn) forControlEvents:UIControlEventTouchUpInside];
    [homeBtn addSubview:backView];
    UIBarButtonItem* barHomeBtn= [[UIBarButtonItem alloc] initWithCustomView:homeBtn];
    self.navigationItem.leftBarButtonItem=barHomeBtn;
    
    UIButton *rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 44, 44)];
    [rightBtn setTitle:@"发布" forState:UIControlStateNormal];
    rightBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    UIBarButtonItem *btnBar = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    [rightBtn addTarget:self action:@selector(fabu) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = btnBar;
    
    playImg = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 40, 40)];
    playImg.center = CGPointMake(videoWidth/2, videoWidth/2);
    [playImg setImage:[UIImage imageNamed:@"videoPlay"]];
    [playerLayer addSublayer:playImg.layer];
    playImg.hidden = YES;
    
    tf = [[UITextField alloc]initWithFrame:CGRectMake(30+videoWidth, 10, self.view.frame.size.width-50-videoWidth, 30)];
    tf.font = [UIFont systemFontOfSize:13];
    tf.placeholder = @"输入心情";
    [self.view addSubview:tf];
    
    [self screenShotUrl:videoURL];
//    UIImageView *v = [[UIImageView alloc]initWithFrame:CGRectMake(50, 150, 150, 150)];
//    v.image = _saveImage;
//    [self.view addSubview:v];
    
}

-(void)fabu{
    NSData * data = [NSData dataWithContentsOfURL:videoURL];
    [self upLoadImage:_saveImage video:data];
}

// 上传
- (void)upLoadImage:(UIImage *)image video:(NSData *)video
{
    //[[THud sharedInstance]showText:@"正在上传"];
    [[THud sharedInstance]showProgress];
    NSData * data1 = UIImagePNGRepresentation(image);
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@", str];
    _img_path = [NSString stringWithFormat:@"/upload/%@.jpg",fileName];
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    [params setObject:fileName forKey:@"serverImgName"];
    if (data1) {
        [params setObject:data1 forKey:@"filename"];
    } else {
        //        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //        _hud.labelText = @"上传失败...";
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            [_hud hide:YES];
        //        });
        //
        //        return;
    }
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:30];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json", @"application/json",@"text/javascript", nil];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString * newUrl = [NSString stringWithFormat:@"%@%@",HOST,@"/yw_uploadify.php"];
    
    [manager POST:newUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (data1) {
            [formData appendPartWithFileData:data1 name:@"filename" fileName:fileName mimeType:@"png"];
            
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *doubi = responseObject;
        NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
        NSLog(@"图片成功%@",shabi);
        [self upLoadVideo:video];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //_hud.labelText = @"上传失败...";
        [[THud sharedInstance]showText:@"上传失败"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_hud hide:YES];
        });
    }];
    
}

// 上传
- (void)upLoadVideo:(NSData *)data
{
    //_hud.labelText = @"正在上传...";
    //[[THud sharedInstance]showText:@"正在上传"];
    [[THud sharedInstance]showProgress];
    [self.view endEditing:YES];
    
    NSMutableDictionary * params = [NSMutableDictionary dictionary];
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    // 设置时间格式
    formatter.dateFormat = @"yyyyMMddHHmmss";
    NSString *str = [formatter stringFromDate:[NSDate date]];
    NSString *fileName = [NSString stringWithFormat:@"%@", str];
    _video_path = [NSString stringWithFormat:@"/v/%@.mp4",fileName];
    [params setObject:fileName forKey:@"serverImgName"];
    if (data) {
        [params setObject:data forKey:@"filename"];
    } else {
        //        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //        _hud.labelText = @"上传失败...";
        //        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        //            [_hud hide:YES];
        //        });
        //        return;
    }
    NSLog(@"%ld",data.length);
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:30];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json", @"application/json",@"text/javascript", nil];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString * newUrl = [NSString stringWithFormat:@"%@%@",HOST,@"/v_upload.php"];
    
    [manager POST:newUrl parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        if (data) {
            [formData appendPartWithFileData:data name:@"filename" fileName:fileName mimeType:@"mp4"];
            
        }
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *doubi = responseObject;
        NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
        NSLog(@"视频成功%@",shabi);
        [self saveImageANdVideoPath];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //_hud.labelText = @"上传失败...";
        [[THud sharedInstance]showText:@"上传失败"];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [_hud hide:YES];
        });
        
    }];
}

- (void)saveImageANdVideoPath
{
    NSUserDefaults*  ud=[[NSUserDefaults alloc] init];
    NSString *str = [ud objectForKey:@"uid"];
    NSDictionary *params = @{
                             @"comment":tf.text.length == 0?@"...":tf.text,
                             @"video_path":_video_path,
                             @"uid":str,
                             @"img_path":_img_path,
                             };
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setTimeoutInterval:30];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/json", @"application/json",@"text/javascript", nil];
    
    manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    NSString * newUrl = [NSString stringWithFormat:@"%@%@",HOST,@"/index.php/appVideo/saveVideoFn"];
    
    [manager POST:newUrl parameters:params success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        if (responseObject) {
            NSData *doubi = responseObject;
            NSString *shabi =  [[NSString alloc]initWithData:doubi encoding:NSUTF8StringEncoding];
            NSLog(@"路径成功%@",shabi);
            //[self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
            //_hud.labelText = @"上传成功...";
            //[[THud sharedInstance]hideHud];
            [[THud sharedInstance]showText:@"上传成功"];
            
            //[self.navigationController popViewControllerAnimated:YES];
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:([self.navigationController.viewControllers count] -3)] animated:YES];
            
        }
    } failure:^(AFHTTPRequestOperation * _Nonnull operation, NSError * _Nonnull error) {
        [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];
        //[[THud sharedInstance]hideHud];
        [[THud sharedInstance]showText:@"上传失败"];
        //dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
         //   [_hud hide:YES];
       // });
    }];
}

-(void)backFn{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)screenShotUrl:(NSURL *)URL
{
    AVURLAsset *urlAsset = [[AVURLAsset alloc] initWithURL:URL options:nil];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:urlAsset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    CMTime time = CMTimeMakeWithSeconds(0.2, 30);
    CGImageRef cgImage = [imageGenerator copyCGImageAtTime:time actualTime:nil error:nil];
    _saveImage = [UIImage imageWithCGImage:cgImage];
}


-(void)playOrPause{
    if (playImg.isHidden) {
        playImg.hidden = NO;
        [player pause];
        
    }else{
        playImg.hidden = YES;
        [player play];
    }
}

- (void)pressPlayButton
{
    [playerItem seekToTime:kCMTimeZero];
    [player play];
}

- (void)playingEnd:(NSNotification *)notification
{
    if (playImg.isHidden) {
        [self pressPlayButton];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
